package com.jic.member.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.orm.Pagination;
import com.jic.common.base.vo.RestResult;
import com.jic.common.utils.IDUtils;
import com.jic.member.constant.enums.DeleteFlagEnum;
import com.jic.member.constant.enums.NodeTemplateTypeEnum;
import com.jic.member.constant.enums.TripTimingJobTypeEnum;
import com.jic.member.entity.TripBranchEntity;
import com.jic.member.entity.TripBranchNodeEntity;
import com.jic.member.entity.TripExecuteInfoEntity;
import com.jic.member.entity.TripNodeTemplateEntity;
import com.jic.member.request.TripBranchNodeEntityRequest;
import com.jic.member.request.TripBranchNodeIdAndTemplateCodeRequest;
import com.jic.member.request.TripBranchNodeIdRequest;
import com.jic.member.response.TripBranchNodeDetailResponse;
import com.jic.member.mapper.*;
import com.jic.member.service.TripBranchNodeService;
import com.jic.member.service.TripTimingJobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wwb
 * @date: 2020/6/5
 */
@Slf4j
@Service("tripBranchNodeService")
public class TripBranchNodeServiceImpl implements TripBranchNodeService {

    @Resource
    private TripEventInfoEntityMapper tripEventInfoEntityMapper;
    @Resource
    private TripExecuteInfoEntityMapper tripExecuteInfoEntityMapper;
    @Resource
    private TripTimingJobService tripTimingJobService;
    @Resource
    private TripBranchNodeEntityMapper tripBranchNodeEntityMapper;
    @Resource
    private TripBranchEntityMapper tripBranchEntityMapper;
    @Resource
    private TripNodeTemplateEntityMapper tripNodeTemplateEntityMapper;
    @Resource
    private TripEntityMapper tripEntityMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Long> updateBranchNode(TripBranchNodeEntityRequest tripBranchNodeEntity) {
        try {
            TripBranchNodeEntity tripBranchNodeEntityVo = new TripBranchNodeEntity();
            BeanUtils.copyProperties(tripBranchNodeEntity, tripBranchNodeEntityVo);
            if (tripBranchNodeEntity.getId() != null) {
                Long branchId = null;
                //如果不创建分支 就根据父级id 查询分支id
                if (tripBranchNodeEntity.getPrevBranchNodeId() != null){
                    TripBranchNodeEntity tripBranchNodeEntity1 = tripBranchNodeEntityMapper.queryById(tripBranchNodeEntity.getPrevBranchNodeId());
                    branchId = tripBranchNodeEntity1.getBranchId();
                }
                if (branchId == null){
                    //取自己的分支id
                    TripBranchNodeEntity tripBranchNodeEntityInfo = tripBranchNodeEntityMapper.queryById(tripBranchNodeEntity.getId());
                    branchId = tripBranchNodeEntityInfo.getBranchId();
                }
                tripBranchNodeEntityVo.setBranchId(branchId);
                tripBranchNodeEntityMapper.update(tripBranchNodeEntityVo);

                //更新下级的分支节点 分支id
                if(tripBranchNodeEntity.getCheckUpdateChild() != null && tripBranchNodeEntity.getCheckUpdateChild()){
                    List<TripBranchNodeEntity> tripBranchNodeEntityList = tripBranchNodeEntityMapper.queryChildByPrevId(tripBranchNodeEntityVo.getId());
                    if (CollectionUtils.isNotEmpty(tripBranchNodeEntityList)){
                        List<Long> ids = tripBranchNodeEntityList.stream().map(TripBranchNodeEntity::getId).collect(Collectors.toList());
                        tripBranchNodeEntityMapper.updateBatchNodeBranchId(ids,branchId);
//                        Long finalBranchId = branchId;
//                        ids.stream().forEach(id->{
//                            tripBranchNodeEntityMapper.update(new TripBranchNodeEntity(){{
//                                setId(id);
//                                setBranchId(finalBranchId);
//                            }});
//                        });

                    }
                }
                return RestResult.success(tripBranchNodeEntityVo.getId());
            } else {
                //判断是否需要创建分支
                Long branchId = null;
                String nodeTemplateCode = tripBranchNodeEntity.getNodeTemplateCode();
                if (NodeTemplateTypeEnum.LABEL_SELECTION_NODE.getCode().equals(nodeTemplateCode)
                        || NodeTemplateTypeEnum.USER_GROUP_SELECTION_NODE.getCode().equals(nodeTemplateCode)
                        || NodeTemplateTypeEnum.EVENT_SELECTION_NODE.getCode().equals(nodeTemplateCode)) {
                    //需要创建分支
                    TripBranchEntity tripBranchEntity = new TripBranchEntity() {{
                        setBranchCode(IDUtils.GenerateBillNo("B"));
                        setTripId(tripBranchNodeEntity.getTripId());
                        setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                        setDeptId(tripBranchNodeEntity.getAdminOperate().getDeptId());
                        setDeptType(tripBranchNodeEntity.getAdminOperate().getDeptType().getCode());
                        setCreateTime(new Date());
                        setCreator(tripBranchNodeEntity.getAdminOperate().getOperator());
                        setCreatorName(tripBranchNodeEntity.getAdminOperate().getOperateName());
                        setUpdator(tripBranchNodeEntity.getAdminOperate().getOperator());
                        setUpdatorName(tripBranchNodeEntity.getAdminOperate().getOperateName());
                    }};
                    tripBranchEntityMapper.insert(tripBranchEntity);
                    branchId = tripBranchEntity.getId();
                }else{
                    //如果不创建分支 就根据父级id 查询分支id
                    if (tripBranchNodeEntity.getPrevBranchNodeId() != null){
                        TripBranchNodeEntity tripBranchNodeEntity1 = tripBranchNodeEntityMapper.queryById(tripBranchNodeEntity.getPrevBranchNodeId());
                        branchId = tripBranchNodeEntity1.getBranchId();
                    }
                }

                //新增分支节点
                TripBranchNodeEntity tripBranchNodeEntityIn = new TripBranchNodeEntity();
                BeanUtils.copyProperties(tripBranchNodeEntity, tripBranchNodeEntityIn);
                tripBranchNodeEntityIn.setNodeCode(IDUtils.GenerateBillNo("N"));
                //查询模板
                TripNodeTemplateEntity nodeTemplateByCode = tripNodeTemplateEntityMapper.getNodeTemplateByCode(tripBranchNodeEntity.getNodeTemplateCode());
                tripBranchNodeEntityIn.setTripId(tripBranchNodeEntity.getTripId());
                tripBranchNodeEntityIn.setNodeTemplateId(nodeTemplateByCode.getId());
                tripBranchNodeEntityIn.setNodeTemplateCode(nodeTemplateByCode.getTemplateCode());
                tripBranchNodeEntityIn.setBranchId(branchId);
                tripBranchNodeEntityIn.setDeptType(tripBranchNodeEntity.getAdminOperate().getDeptType().getCode());
                tripBranchNodeEntityIn.setDeptId(tripBranchNodeEntity.getAdminOperate().getDeptId());
                tripBranchNodeEntityIn.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                tripBranchNodeEntityIn.setCreateTime(new Date());
                tripBranchNodeEntityIn.setCreator(tripBranchNodeEntity.getAdminOperate().getOperator());
                tripBranchNodeEntityIn.setCreatorName(tripBranchNodeEntity.getAdminOperate().getOperateName());
                tripBranchNodeEntityIn.setUpdator(tripBranchNodeEntity.getAdminOperate().getOperator());
                tripBranchNodeEntityIn.setUpdatorName(tripBranchNodeEntity.getAdminOperate().getOperateName());
                tripBranchNodeEntityIn.setUpdateTime(new Date());
                tripBranchNodeEntityMapper.insert(tripBranchNodeEntityIn);
                return RestResult.success(tripBranchNodeEntityIn.getId());
            }
        } catch (Exception e) {
            log.error("新增/编辑分支节点出错===============?>>>>>>>>>>>>>>>>>>>>>{}", e);
            return RestResult.error("9999", "新增/编辑分支节点出错...");
        }
    }

    @Override
    public RestResult<Boolean> delBranchNode(TripBranchNodeIdAndTemplateCodeRequest tripBranchNodeIdRequest) {
        try {
            //先去查询模板是否有分支
            TripNodeTemplateEntity nodeTemplateByCode = tripNodeTemplateEntityMapper.getNodeTemplateByCode(tripBranchNodeIdRequest.getNodeTemplateCode());
            if (nodeTemplateByCode == null) {
                return RestResult.error("9999", "不存在的模板");
            }
            //查询分支节点
            TripBranchNodeEntity tripBranchNodeEntity = tripBranchNodeEntityMapper.queryById(tripBranchNodeIdRequest.getBranchNodeId());

            if (NodeTemplateTypeEnum.LABEL_SELECTION_NODE.getCode().equals(nodeTemplateByCode.getTemplateCode())
                    || NodeTemplateTypeEnum.USER_GROUP_SELECTION_NODE.getCode().equals(nodeTemplateByCode.getTemplateCode())
                    || NodeTemplateTypeEnum.EVENT_SELECTION_NODE.getCode().equals(nodeTemplateByCode.getTemplateCode())) {
                //删除分支
                tripBranchEntityMapper.update(new TripBranchEntity() {{
                    setId(tripBranchNodeEntity.getBranchId());
                    setDeleteFlag(DeleteFlagEnum.DELETE.getCode());
                }});
            }
            //删除分支节点数据
            tripBranchNodeEntityMapper.update(new TripBranchNodeEntity() {{
                setId(tripBranchNodeEntity.getId());
                setDeleteFlag(DeleteFlagEnum.DELETE.getCode());
            }});
            //更新下级节点
            log.info("删除下级节点的父id=====================.....{}",tripBranchNodeEntity.getId());
            tripBranchNodeEntityMapper.updateChildByPid(tripBranchNodeEntity.getId());

            return RestResult.success(true);
        } catch (Exception e) {
            log.error("删除分支节点报错====>>>>>>>>>>>>>>>>>>>>>{}", e);
            return RestResult.error("9999", "删除分支节点错误");
        }
    }

    @Override
    public void exeCheckSellTrue(TripBranchNodeEntity node, String thirdUserId) {
        // 查询出下一个节点
        TripBranchNodeEntity tripBranchNodeEntityQ = new TripBranchNodeEntity();
        tripBranchNodeEntityQ.setBranchCondition(1);
        tripBranchNodeEntityQ.setPrevBranchNodeId(node.getId());
        TripBranchNodeEntity tripBranchNodeEntity = tripBranchNodeEntityMapper.query(tripBranchNodeEntityQ);
        tripTimingJobService.register(TripTimingJobTypeEnum.EXE_ACTION, tripBranchNodeEntity.getNodeTemplateCode(), tripBranchNodeEntity.getId(), null, "核销成功触发下一个节点", tripBranchNodeEntity, thirdUserId);
    }

    @Override
    public void exeCheckSellFalse(TripBranchNodeEntity node) {
        log.info("进入事件判断失败节点");
        // 查询出下一个节点
        TripBranchNodeEntity tripBranchNodeEntityQ = new TripBranchNodeEntity();
        tripBranchNodeEntityQ.setBranchCondition(2);
        tripBranchNodeEntityQ.setDeleteFlag(0);
        tripBranchNodeEntityQ.setPrevBranchNodeId(node.getId());
        TripBranchNodeEntity tripBranchNodeEntity = tripBranchNodeEntityMapper.query(tripBranchNodeEntityQ);
        // 查询出该旅程分支下的所有用户，考虑到数据量，我们一次性查100条，并分批放入job中
        List<TripExecuteInfoEntity> tripPeopleEntityList;
        int pageNo = 1;
        do {
            TripExecuteInfoEntity tripExecuteInfoEntityQ = new TripExecuteInfoEntity();
            tripExecuteInfoEntityQ.setBranchId(node.getBranchId());
            tripExecuteInfoEntityQ.setBranchNodeId(node.getPrevBranchNodeId()); // 上一个执行动作的nodeId
            Pagination pagination = new Pagination();
            pagination.setPageNo(pageNo);
            pagination.setPageSize(100);
            pagination.setOrderBy("id");
            tripPeopleEntityList = tripExecuteInfoEntityMapper.findOfPage(tripExecuteInfoEntityQ, pagination);
            // 注册Job
            if((null != tripPeopleEntityList && !tripPeopleEntityList.isEmpty())){
                List<String> allThirdUserIdList = tripPeopleEntityList.stream().map(TripExecuteInfoEntity::getThirdUserId).collect(Collectors.toList());
                // 排除掉与取当前事件节点的id相关的事件数据，就是要的数据
                List<String> thirdUserIdList  = tripEventInfoEntityMapper.queryNotRepeatThridUserId(node.getId(), allThirdUserIdList);
                if(null != thirdUserIdList && !thirdUserIdList.isEmpty()){
                    tripTimingJobService.register(TripTimingJobTypeEnum.EXE_ACTION, tripBranchNodeEntity.getNodeTemplateCode(), tripBranchNodeEntity.getId(), null, "时间判断失败节点", tripBranchNodeEntity.getTripId(),tripBranchNodeEntity.getId(), thirdUserIdList);
                }
            }
            pageNo++;
        }while (null != tripPeopleEntityList && !tripPeopleEntityList.isEmpty());

    }

    @Override
    public RestResult<TripBranchNodeDetailResponse> getBranchNodeDetail(TripBranchNodeIdRequest tripBranchNodeIdRequest) {
        try {
            TripBranchNodeEntity tripBranchNodeEntity = tripBranchNodeEntityMapper.queryById(tripBranchNodeIdRequest.getBranchNodeId());
            if (tripBranchNodeEntity == null){
                return RestResult.error("9999","分支节点不存在");
            }else if (tripBranchNodeEntity.getDeleteFlag().equals(DeleteFlagEnum.DELETE.getCode())){
                return RestResult.error("9999","分支节点已被删除");
            }
            TripBranchNodeDetailResponse tripBranchNodeDetailResponse = new TripBranchNodeDetailResponse();
            BeanUtils.copyProperties(tripBranchNodeEntity,tripBranchNodeDetailResponse);
            return RestResult.success(tripBranchNodeDetailResponse);
        }catch (Exception e){
            log.error("查询分支节点信息错误....++++++++++++++++==============?>>>>>>>{}",e);
            return RestResult.error("9999","查询分支节点信息失败");
        }
    }

    /**
     * 校验是否用户组是否可删除
     * @param userGroupId
     * @return
     */
    @Override
    public Boolean checkUserGroup(Long userGroupId) {
        Boolean flag = false;
        //获取分支及分支下节点
        List<Long> branchIds = tripBranchEntityMapper.getAvailableIds();
        List<TripBranchNodeEntity> branchNodeList = tripBranchNodeEntityMapper.queryByBranchIds(branchIds).stream()
                .filter(x ->null!=x.getNodeVariable()).collect(Collectors.toList());
        outterLoop: for(TripBranchNodeEntity branchNode : branchNodeList){
            //判断用户组节点
            if(NodeTemplateTypeEnum.USER_GROUP_SELECTION_NODE.getCode().equals(branchNode.getNodeTemplateCode())){
                //解析JSON
                JSONObject map = JSONObject.parseObject(branchNode.getNodeVariable());
                List userGroupList = map.getJSONArray("tripUserGroupRequestList");
                for(int i = 0; i < userGroupList.size(); i++ ){
                    Map<String,String > userGroupMap = JSONArray.parseObject(String.valueOf(userGroupList.get(i)),Map.class);
                    if(userGroupId.toString().equals(userGroupMap.get("userGroupId"))){
                        flag = true;
                        break outterLoop; //结束循环
                    }
                }
            }
        }
        return flag;
    }

    @Override
    public void deleteNodeTopLeftByTripId(Long tripId) {

        tripBranchNodeEntityMapper.deleteNodeTopLeftByTripId(tripId);

        List<TripBranchEntity> tripBranchEntityList = tripBranchEntityMapper.findAll(new TripBranchEntity() {{
            setTripId(tripId);
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        }});
        for (TripBranchEntity tripBranchEntity : tripBranchEntityList) {
            //查询分支下是否有节点
            List<TripBranchNodeEntity> nodeList = tripBranchNodeEntityMapper.findAll(new TripBranchNodeEntity() {{
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setBranchId(tripBranchEntity.getId());
            }});
            if(CollectionUtils.isEmpty(nodeList)){
                tripBranchEntityMapper.update(new TripBranchEntity(){{
                    setId(tripBranchEntity.getId());
                    setDeleteFlag(DeleteFlagEnum.DELETE.getCode());
                }});
            }
        }
    }
}
